package com.hiyee.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hiyee.admin.mapper.AdminUserMapper;
import com.hiyee.admin.service.AdminUserService;
import com.hiyee.exception.GraceException;
import com.hiyee.grace.result.ResponseStatusEnum;
import com.hiyee.pojo.AdminUser;
import com.hiyee.pojo.bo.UpdateAdminUserBO;
import com.hiyee.service.BaseService;
import com.hiyee.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class AdminUserServiceImpl extends BaseService implements AdminUserService {

    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    Sid sid;

    @Override
    public AdminUser getByUsername(String username) {
        Example example = new Example(AdminUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        return adminUserMapper.selectOneByExample(example);
    }

    @Override
    public void createAdminUser(UpdateAdminUserBO adminUserBO) {
        String id = sid.nextShort();

        AdminUser adminUser = new AdminUser();
        adminUser.setId(id);
        adminUser.setAdminName(adminUserBO.getAdminName());
        adminUser.setUsername(adminUserBO.getUsername());

        if(StringUtils.isNoneBlank(adminUserBO.getPassword())) {
            adminUser.setPassword(BCrypt.hashpw(adminUserBO.getPassword(), BCrypt.gensalt()));
        }

        if(StringUtils.isNotBlank(adminUserBO.getFaceId())) {
            adminUser.setFaceId(adminUserBO.getFaceId());
        }

        adminUser.setCreatedTime(new Date());
        adminUser.setUpdatedTime(new Date());

        int result = adminUserMapper.insert(adminUser);
        if(result != 1) {
            GraceException.display(ResponseStatusEnum.ADMIN_USER_ADD_FAIL);
        }
    }

    @Override
    public PagedGridResult getAdminList(Integer page, Integer pageSize) {
        Example example = new Example(AdminUser.class);
        example.orderBy("createdTime").desc();
        Example.Criteria criteria = example.createCriteria();
        PageHelper.startPage(page, pageSize);
        List<AdminUser> adminUserList = adminUserMapper.selectByExample(example);
        PagedGridResult pagedGridResult = this.getPageResult(adminUserList, page, pageSize);
        return pagedGridResult;
    }
}
